import { defineStore } from 'pinia'
import type { Router } from 'vue-router'
import { getAllBreadcrumbList, getFlatMenuList, getShowMenuList } from '@/utils'

export const useRouteStore = defineStore('store-route', () => {
  // 授权路由列表
  const routeList = ref<Menu.MenuOptions[]>([])
  // 当前页面的 router name，用来做按钮权限筛选

  // 路由列表 ==> 左侧菜单栏渲染，剔除隐式路由
  const menuList = computed(() => getShowMenuList(routeList.value))
  // 菜单列表 ==> 扁平化之后的一维数组菜单，用来添加动态路由
  const flatMenuList = computed(() => getFlatMenuList(routeList.value))
  // 递归处理后的所有面包屑导航列表
  const breadcrumbList = computed(() => getAllBreadcrumbList(routeList.value))

  // 获取路由
  function setMenuList(routes) {
    routeList.value = routes
  }

  // 移除所有路由
  function resetRouter(router: Router) {
    flatMenuList.value.forEach(({ name }) => {
      if (name && router.hasRoute(name))
        router.removeRoute(name)
    })
    routeList.value = []
  }

  return { routeList, menuList, flatMenuList, breadcrumbList, resetRouter, setMenuList }
})
